package com.topnav.mc.admin.security.jwt;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.topnav.mc.admin.dao.mapper.PermissionMapper;
import com.topnav.mc.admin.entity.Permission;
import com.topnav.mc.admin.entity.User;
import com.topnav.mc.admin.service.IUserService;
import com.topnav.mc.exception.ExceptionMsg;
import com.topnav.mc.uitls.ExceptionUtil;
import com.topnav.mc.uitls.PasswordUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 说明：
 * @类名: JwtUserDetailServiceImpl
 * <p>
 *  自定义UserDetailsService 接口
 * </p>
 * @author   kenny
 * @Date	 2022年2月10日上午11:33:45
 */
@Service
public class JwtUserDetailService implements UserDetailsService {
	@Autowired
	private PermissionMapper permissionMapper;
	@Autowired
	private IUserService userService;
	//@Resource
	@Autowired
	private PasswordEncoder passwordEncoder;

	/**
	 * 从数据库取得该用户的权限
	 */
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException{
		if (StringUtils.isEmpty(username)){
			throw ExceptionUtil.commonException(ExceptionMsg.ERROR_AUTHENTICATION_NOT_EXISTS_USER, username) ;
		}
		User user = null;
		if ("super".equals(username)){
			user = new User();
			user.setCode("super");
			user.setName("super");
			user.setLoginName("super");
			user.setEnabledNotify(true);
			user.setPassword(passwordEncoder.encode(PasswordUtil.superPwd));
			user.setEnabled(true);
		}else{
			QueryWrapper<User> wrapper = new QueryWrapper<User>();
			wrapper.eq("login_name", username);
			user = userService.getOne(wrapper, false);
		}

		if (user == null){
			/** 不存在的用户  {userName}*/
			throw ExceptionUtil.commonException(ExceptionMsg.ERROR_AUTHENTICATION_NOT_EXISTS_USER, username) ;
		}

		//禁止登录
		if (!user.getEnabled()){
			throw ExceptionUtil.commonException(ExceptionMsg.ERROR_AUTHENTICATION_ENABLED_FAILE, username);
		}

		List<Permission> pmList=null;
		/** 系统管理 拥有 全部权限 */
		if (("ADMIN").equals(username.toUpperCase()) || ("SUPER").equals(username.toUpperCase())){
			pmList = permissionMapper.findAllPermission();
		}else{
			pmList = permissionMapper.findPermissionByUserId(user.getId());
		}

		List<GrantedAuthority> grantedAuthorities = new ArrayList <>();
		for (Permission permission : pmList) {
            if (permission != null && permission.getPmCode()!=null) {
            	GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission.getPmCode());
                grantedAuthorities.add(grantedAuthority);
            }
        }
		return new JwtUser(user.getLoginName(),user.getPassword(),grantedAuthorities);
	}

}
